//点餐效果
//获取应用实例
const app = getApp()

Page({
  data: {
    imgUrls: [
      'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
    ],
    foodTypes: ['全部菜品', '披萨', '面条', '水果', '寿司', '三明治'],
    foodTypesIndex:0,
    rankTypes: ['综合排序', '热度', '价格', '评价', '时间'],
    rankTypesIndex:0,
    foodList:[],
    orderNum:0,
    orderCost:0,
    orderList:{}
  },
  onLoad: function () {
    let originData = app.globalData.foodList;
    // let foodList = [];
    // for (var i = 0; i < originData.length;i++){
    //   foodList.push(originData[i]);
    // }
    this.setData({ foodList: originData})
  },
  foodTypeChange(e){
    console.log(e);
    this.setData({
      foodTypesIndex: e.detail.value
    });
  },
  rankTypeChange(e){
    this.setData({
      rankTypesIndex: e.detail.value
    });
  },
  addToCart:function(e){
    //console.log(e);
    var dataset = e.currentTarget.dataset;
    this.changeNum(dataset.index,true);
    wx.showToast({
      title: '已添加',
      icon:'success',
      duration:1000
    })
  },
  reduceFromCart:function(e){
    //console.log(e);
    var dataset = e.currentTarget.dataset;
    wx.showToast({
      title: '已删除',
      icon: 'success',
      duration: 1000
    })
    this.changeNum(dataset.index, false);
  },
  changeNum:function(index,bool){
    let t_food = this.data.foodList[index];
    let orderList = this.data.orderList;
    let obj = orderList[t_food.id];

    //如果存在则数量变化
    if(obj){
      if(bool){
        obj.num+=1;
      }else{
        if(obj.num>0){
          obj.num = obj.num - 1;
        }else{
          return ;//以减少为0
        }
      }
    }else{
      if(bool){
        //不存在,点击添加,写入一条订单，数量为1
        obj = {
          id:t_food.id,
          num:1,
          cost:t_food.cost,
          title:t_food.title
        }
        orderList[t_food.id] = obj;
      }else{
        return;//不存在该订单
      }
    }

    var order_num = 0;
    var order_cost = 0;
    for(var k in orderList){
      order_num = orderList[k].num + order_num;
      order_cost = order_cost + orderList[k].cost * orderList[k].num;
    }

    t_food.num = obj.num;
    let foodList = this.data.foodList;
    foodList[index] = t_food;//更新数据源
    console.log(orderList);
    this.setData({
      orderList: orderList,
      orderNum: order_num,
      orderCost: order_cost,
      foodList: foodList
    });
  }
})
